using BestHTTP.SocketIO;
using BestHTTP.WebSocket;
using PureMVC.Interfaces;
using PureMVC.Patterns.Observer;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using Notification = PureMVC.Patterns.Observer.Notification;

namespace WooEngine.NetWork.Provider
{
    public class WebSocketProvider : Notifier, INetWorkProvider
    {
        private Uri m_uri;
        private WebSocket m_webSocket;
        private Action<string> m_ConnectCallBack;

        private Queue<Notification> m_result_que;

        public string Tag { get; private set; }

        public bool IsCanOP
        {
            get
            {
                return m_webSocket != null && m_webSocket.IsOpen;
            }
        }

        public byte[] Token { get; private set; }

        public long UID { get; private set; }

        private SocketManager manager;
        public WebSocketProvider(string tag, string url, string port = null)
        {
            Tag = tag;
            m_uri = new Uri(port == null ? url : StringUtils.AppendString(url, ":", port));
            m_result_que = new Queue<Notification>();
        }

        public void Connect(Action<string> callBack)
        {
            m_ConnectCallBack = callBack;
            m_webSocket = new WebSocket(m_uri);
#if !UNITY_WEBGL
            m_webSocket.StartPingThread = true;
#endif
            m_webSocket.OnOpen += OnOpen;
            m_webSocket.OnBinary += OnBinary;
            m_webSocket.OnClosed += OnClosed;
            m_webSocket.OnError += OnError;

            m_webSocket.Open();


        }

        private void OnError(WebSocket webSocket, string reason)
        {
            throw new NotImplementedException();
        }

        private void OnClosed(WebSocket webSocket, ushort code, string message)
        {
            m_webSocket = null;
        }

        private void OnBinary(WebSocket webSocket, byte[] data)
        {
            //Notification notification = new Notification();

        }

        private void OnOpen(WebSocket webSocket)
        {
            if(m_ConnectCallBack != null)
            {
                m_ConnectCallBack(Tag);
            }
        }

        public  void Recv()
        {
            if (!IsCanOP)
                return;
            while(m_result_que.Count > 0)
            {
                Notification revNot = m_result_que.Dequeue();
                if(revNot != null)
                {
                    SendNotification(revNot.Name, revNot.Body);
                }
            }
        }

        public  void Release()
        {
            m_webSocket.Close();
        }

        public void Send(string smname, byte[] data, bool isWaitReceive)
        {
            if (isWaitReceive)
            {

            }
            m_webSocket.Send(data);
        }

        public void SetUserInfo(long uid, byte[] token)
        {
            throw new NotImplementedException();
        }
    }
}